package com.hx.alipay.controller;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.google.common.collect.Maps;
import com.hx.alipay.pojo.OrderItem;
import com.hx.alipay.pojo.User;
import com.hx.alipay.services.OrderItemService;
import com.hx.alipay.services.OrderService;
import com.hx.alipay.util.Const;

@Controller
@RequestMapping("/order/")
public class OrderController {

	org.slf4j.Logger logger = LoggerFactory.getLogger(OrderController.class);

	@Autowired
	private OrderItemService orderItemService;
	@Autowired
	private OrderService orderService;

	@RequestMapping("create")
	public String createOrder() {
		/*
		 * 1. 创建订单[获取购物车中选中商品的ID和商品数量] 2.
		 * 根据选中的商品ID在order表中添加数据，并将订单详细信息保存在order_item表中 3. 页面跳转到订单确认页面
		 */
		logger.info("~~~创建建订单~~~{}", 10);

		return "redirect:/order/detail?orderNo=2017062816010251581";
	}

	@RequestMapping("detail")
	public String getOrderDetail(HttpSession session, Long orderNo, Map<String, Object> map) {
		User user = (User) session.getAttribute(Const.CURRENT_USER);
		if (null == user) {
			map.put("msg", "用户为登录，请先登录！");
			return "login";
		}
		List<OrderItem> orderItemList = orderItemService.findOrderItem(user.getId(), orderNo);
		map.put("orderDetailMap", orderItemList);

		return "order_checking";
	}

	@RequestMapping("pay")
	public String pay(HttpSession session, Long orderId, HttpServletRequest request, Map<String, Object> map) throws IOException {
		User user = (User) session.getAttribute(Const.CURRENT_USER);
		if (null == user) {
			map.put("msg", "用户为登录，请先登录！");
			return "login";
		}

		String path = request.getSession().getServletContext().getRealPath("uploadimages");

		Map<String, Object> resultMap = orderService.pay(path);

		map.put("msg", "success");
		map.put("fileName", resultMap.get("fileNamePath"));
		map.put("filePath", resultMap.get("filePath"));

		return "pay";
	}

	@RequestMapping("alipay_callback")
	public String alipayCallback(HttpServletRequest request, Map<String, Object> map) {
		Map<String, String> params = Maps.newHashMap();

		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";

			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}
		System.out.println("-------------------------------------------------------");
		logger.info("支付宝回调,sign:{},trade_status:{},参数:{" + JSON.toJSONString(params) + "}", params.get("sign"), params.get("trade_status"));
		System.out.println("-------------------------------------------------------");
		// 验证回调的争正确性，是不是支付宝发的，并且还要避免重复通知【非常重要】
		params.remove("sign_type");
		try {
			boolean alipayRSACheckedV2 = AlipaySignature.rsaCheckV2(params, Configs.getAlipayPublicKey(), "utf-8", Configs.getSignType());
			if (!alipayRSACheckedV2) {
				// return
				// ServerResponse.createByErrorMessage("非法请求，验证不通过，在恶意请求就报警");
			}
			// 减少库存，修改订单状态
			// 编写业务逻辑

			// ServerResponse serverResponse =
			// iOrderService.aliCallback(params);
			// if (serverResponse.isSucces()) {
			// return Const.AlipayCallback.RESPONSE_SUCCESS;
			// }
			// return Const.AlipayCallback.RESPONSE_FAILED;
		} catch (AlipayApiException e) {
			logger.error("支付宝验证回调异常", e);
		}
		return null;
	}

}
